//
//  ZHNetWorkTools.swift
//  网络工具类(Swift版)
//
//  Created by zhangzhen on 16/6/5.
//  Copyright © 2016年 zhangzhen. All rights reserved.
//
import UIKit
import AFNetworking

//定义枚举
enum ZHRequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}

class ZHNetWorkTools: AFHTTPSessionManager {
    // MARK: - 应用程序基本信息
    private let appKey = "3187109239"
    private let appSecret = "aa57f3359c57db9ed4a05b8b1964d89b"
    private let redirectUrl = "http://www.baidu.com"
    
    //起别名
    typealias ZHRequestCallBack = (result: AnyObject?,error: NSError?) ->()
    /// token 字典
    /// 返回 token 字典
    private var tokenDict: [String: AnyObject]? {
        // 判断 token 是否有效
        if let token = ZHUserAccountViewModel.shareUserAccount.accessToken {
            
            return ["access_token": token]
        }
        
        return nil
    }
    
    //创建单例对象
    static let sharetools : ZHNetWorkTools = {
        
       let tools = ZHNetWorkTools(baseURL: nil)
        tools.responseSerializer = AFJSONResponseSerializer()
     tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/JavaScript",@"text/html",@"text/plain", nil];
        return tools
    }()

}
// MARK: - 登录请求方法
extension ZHNetWorkTools{
    //拼接不同的URL
    var ouauthURL : NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
       return NSURL(string: urlString)!
    }
    //网络请求加载accessToken
    func loadAccessToken(code: String,finished: ZHRequestCallBack) {
        
        let parameters = ["client_id": appKey,
                          "client_secret":appSecret,
                          "grant_type":"authorization_code",
                          "code": code,
                          "redirect_uri": redirectUrl]
        request(.POST, URLString: "https://api.weibo.com/oauth2/access_token", parameters: parameters, finished: finished)
    }
    
    //网络请求获取用户的信息
    func loadUserInfo(uid: String, finished: ZHRequestCallBack) {
        
        // 1. 获取 token 字典
        guard var params = tokenDict else {
            
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        params["uid"] = uid
        
        request(.GET, URLString: urlString, parameters: params, finished: finished)
        
    }
    
}
// MARK: - 网络请求
extension ZHNetWorkTools{
    
    
    func request(requestMethod: ZHRequestMethod, URLString: String, parameters: [String : AnyObject]?, finished: ZHRequestCallBack) {
        //成功回调
        let success  = {(task: NSURLSessionDataTask,result:AnyObject?) in
         finished(result: result, error: nil)
            
        }
        let failure = {(task: NSURLSessionDataTask?,error: NSError) in
            finished(result: nil, error: error)
        }
        
       
        
       //发送GET请求的方法
        if requestMethod == ZHRequestMethod.GET{
            
          GET(URLString, parameters: parameters, success: success, failure: failure)
        }else{
          POST(URLString, parameters: parameters, success: success, failure: failure)
            
            
            
        }
    }
    
}
